import './index.less';
import Button from 'antd/es/button';
import Input from 'antd/es/input';
import { useState } from 'react';
import { AppStore, EViewType, IViewInfo } from '../../store';
import { Collapse, TriggerPosition } from '../../components';
import Tabs from 'antd/es/tabs';
import message from 'antd/es/message';
import { ToolType } from '@manycore/custom-ksg-viewer-sdk';

export function LeftPanel() {
    const { appState: { app }, updateViewInfo, updateJsonData } = AppStore.useContainer();


    const [activeKey, setActiveKey] = useState<EViewType>(EViewType.Design);
    const [designId, setDesignId] = useState<string>();
    const [modelId, setModelId] = useState<string>();
    const [auditDesign, setAuditDesign] = useState<string>();
    const [orderId, setOrderId] = useState<string>();
    const [loading, setLoading] = useState<boolean>(false);

    async function getDesignViewJson(viewData: IViewInfo) {
        let data: { url: string } | null = null;
        updateJsonData(undefined);
        const { type, info } = viewData;
        if (type === EViewType.Design) {
            const { designId, modelId } = info;
            data = (await Manycore.Custom.Design.Export.getModelJsonUrlAsync({
                designId,
                modelIds: modelId,
            })).data;
        } else if (type === EViewType.AuditDesign || type === EViewType.AuditOrder) {
            data = (await Manycore.Custom.Design.Export.getAuditDesignJsonUrlAsync(info)).data;
        }
        if (data?.url) {
            const json = await fetch(data.url, { method: 'get' }).then(res => res.json());
            const { levelToolTypeResultList } = json;
            if (levelToolTypeResultList && Array.isArray(levelToolTypeResultList)) {
                updateJsonData(levelToolTypeResultList[0]?.productionData);
            }
        }
    }

    async function openViewer(viewData: IViewInfo) {
        
        /** 订单默认的工具线,填写实际订单工具线 */
        const defaultOrderToolTypes = [ToolType.Cabinet, ToolType.Wardrobe];
        try {
            setLoading(true);
            const { type, info } = viewData;
            if (type === EViewType.Design) {
                const { designId, modelId } = info;
                updateViewInfo({
                    type: EViewType.Design,
                    info: info
                });
                await app!.sceneService.viewAsync({
                    designId: designId,
                    modelId: modelId,
                });

            } else if (type === EViewType.AuditDesign) {
                const { auditDesignId } = info;
                updateViewInfo({
                    type: EViewType.AuditDesign,
                    info: info
                });
                await app!.sceneService.viewAsync({ 
                    auditDesignId,
                    toolType: defaultOrderToolTypes
                 });
            } else if (type === EViewType.AuditOrder) {
                const { orderId } = info;
                updateViewInfo({
                    type: EViewType.AuditOrder,
                    info: info
                });
                await app!.sceneService.viewAsync({ 
                    orderId,
                    toolType: defaultOrderToolTypes
                 });
            }
        } catch (err) {
            console.error(err);
        } finally {
            setLoading(false);
        }
    }

    const items = [
        {
            label: '设计方案', key: EViewType.Design, children: <div className='left-panel-main'>
                <span className='bold-text'>方案ID</span>
                <Input value={designId} onChange={(event) => setDesignId(event.target.value)} size='small'></Input>
                <span className='bold-text'>主对象模型ID</span>
                <Input value={modelId} onChange={(event) => setModelId(event.target.value)} size='small'></Input>
            </div>
        },
        {
            label: '审核方案', key: EViewType.AuditDesign, children: <div className='left-panel-main'>
                <span className='bold-text'>审核方案ID</span>
                <Input value={auditDesign} onChange={(event) => setAuditDesign(event.target.value)} size='small'></Input>
            </div>
        },
        {
            label: '审核订单', key: EViewType.AuditOrder, children: <div className='left-panel-main'>
                <span className='bold-text'>审核订单ID</span>
                <Input value={orderId} onChange={(event) => setOrderId(event.target.value)} size='small'></Input>

            </div>
        },
    ];


    const onClick = () => {
        let viewInfo: IViewInfo | undefined = undefined;
        if (activeKey === EViewType.Design) {
            if (!designId || !modelId) {
                message.error('designId or modelId not exist!');
                return;
            };
            viewInfo = {
                type: activeKey,
                info: {
                    designId: designId,
                    modelId: modelId
                }
            }
        } else if (activeKey === EViewType.AuditDesign) {
            if (!auditDesign) {
                message.error('auditDesignId not exist!');
                return;
            }
            viewInfo = {
                type: activeKey,
                info: {
                    auditDesignId: auditDesign
                }
            };
        } else if (activeKey === EViewType.AuditOrder) {
            if (!orderId) {
                message.error('orderId not exist!');
                return;
            }
            viewInfo = {
                type: activeKey,
                info: {
                    orderId: orderId
                }
            }
        }
        if (viewInfo) {
            openViewer(viewInfo);
            getDesignViewJson(viewInfo);
        }
    }


    return (

        <Collapse triggerPosition={TriggerPosition.Right} className='left-panel-collapse'>
            <div className='left-panel-main'>
                <Tabs activeKey={activeKey} onChange={(a) => setActiveKey(a as EViewType)} size='small' items={items} className='right-panel-tab' />
                <Button loading={loading} onClick={onClick} type="primary" size='small' className='left-panel-main-button'>确认</Button>
            </div>
        </Collapse>

    )
}
